package com.sgb.kjwl.view.ui.activity.self;

import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPersonInfoBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.user.UserBaseEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.adapter.self.SelfEnterprisesListAdapter;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.ChangeMobileActivity;

import com.sgb.kjwl.view.ui.adapter.self.EnterprisesListAdapter;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow;
import com.sgb.kjwl.viewmodel.self.PersonInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import static android.view.View.GONE;

/*
个人中心的界面
 */
public class PersonInfoActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener, XRecyclerView.LoadingListener{
    //相册选择弹窗
    SelectAlbumPopWindow selectAlbumPopWindow;
    private ActivityPersonInfoBinding binding;
    List<LocalMedia> selectionMedia = new ArrayList<>();
    //公司列表标记
    public static String CompanyCode = "CompanyCode";
    //用户基本信息标记
    public static String UserEntityCode = "userEntityCode";
    private List<CompanyEntity> mCompanyEntityList;
    private int CompanyrequestCode = 1000;
    private int SwitchingCode = 1001;
    private List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> baseAreaEntityList;
    private int sexPosition;
    private boolean isPersonAuth;
    private boolean isEdit;
    private List<CompanyEntity> mlist= new ArrayList<>();
    @Inject
    PersonInfoModel viewModel;
    private String avatar;
    private String entityImage;
    //用户基本信息
    UserBaseEntity mUserEntity;

    private RequestManager requestManager;
    private  int  from=-1;
    private int page=1;
    private int limit=10;
    private SelfEnterprisesListAdapter enterprisesListAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //设置状态栏为暗
    @Override
    protected boolean statusBarDark() {
        return true;
    }

    //跳转
    public static void start(Context context, List<CompanyEntity> companyEntityList) {
        Intent intent = new Intent();
        intent.setClass(context, PersonInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(CompanyCode, (Serializable) companyEntityList);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
    //跳转
    public static void start(Context context, List<CompanyEntity> companyEntityList,int from) {
        Intent intent = new Intent();
        intent.setClass(context, PersonInfoActivity.class);
        intent.putExtra(CompanyCode, (Serializable) companyEntityList);
        intent.putExtra("from",from);
        context.startActivity(intent);
    }

    /**
     * 跳转带参数（公司列表）
     */
    public static void startActivity(Context context, List<CompanyEntity> companyEntityList) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(CompanyCode, (Serializable) companyEntityList);
        intent.putExtras(bundle);
        intent.setClass(context, PersonInfoActivity.class);
        context.startActivity(intent);
    }

    //获取屏幕焦点时
    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = this.getIntent();
        mCompanyEntityList = (List<CompanyEntity>) intent.getSerializableExtra(CompanyCode);
//        mUserEntity = (EssentiaIinformationeEntity) intent.getSerializableExtra(UserEntityCode);
        if (mUserEntity == null) {
            viewModel.getEssentialInformation();
        } else {
            showHeadPortrait(mUserEntity);
        }
     /*   if (mCompanyEntityList.size() > 0) {
            showCompanyList(mCompanyEntityList);
        } else {
            binding.tvLine.setVisibility(View.GONE);
        }*/
    }


    @Override
    protected void initView() {
        requestManager =  Glide.with(this);
        //双向绑定Activity和View
        binding = DataBindingUtil.setContentView(PersonInfoActivity.this, R.layout.activity_person_info);
        //绑定ViewModel
        binding.setViewModel(viewModel);
        //判断公司选择弹出窗口是否存在
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow(PersonInfoActivity.this);
        }
        //设置背景
        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 0) {
                    openAlbum();
                    selectAlbumPopWindow.dismiss();
                }
            }
        });
        //请求头像信息
//        viewModel.getEssentialInformation();
    }

    @Override
    protected void init() {
        from =getIntent().getIntExtra("from",-1);
        //设置头部信息
        if (from==-1){
            binding.include.titleView.setText("我的信息");
            binding.llBase.setVisibility(View.VISIBLE);
            binding.llCom.setVisibility(GONE);
        }else {
            binding.include.titleView.setText("我的组织");
            binding.include.rightView.setText("员工加入");
            binding.llBase.setVisibility(GONE);
            binding.llCom.setVisibility(View.VISIBLE);
        }
        //设置点击事件
        binding.include.rightView.setOnClickListener(this);
        //返回按钮的事件
        binding.include.ivBack.setOnClickListener(this);
        //修改手机号码（暂时取消）
        binding.llChangeMobile.setOnClickListener(this);
        //修改密码（暂时取消）
        binding.llChangePwd.setOnClickListener(this);
        //设置企业列表管理器
        binding.rvEnterprisesList.setLayoutManager(new LinearLayoutManager(this));
        binding.rvEnterprisesList.setLoadingMoreEnabled(true);
        binding.rvEnterprisesList.setLoadingListener(this);
        //设置title的点击事件（暂时取消）
        binding.include.titleView.setOnClickListener(this);
        //设置主公司的点击事件
        binding.mainCorporate.setOnClickListener(this);
        //设置上传头像的点击事件
        binding.ivUserName.setOnClickListener(this);
        binding.itemTvPhone.setOnWholeItemClickListener(this);

        binding.nextView.setOnClickListener(this);
        binding.tvClick.setOnClickListener(this);
        binding.tvClick2.setOnClickListener(this);
        binding.itemTvSex.setOnWholeItemClickListener(this);
        binding.itemTvAge.setOnWholeItemClickListener(this);
        binding.itemTvCompany.setOnWholeItemClickListener(this);
        binding.itemTvName.setOnWholeItemClickListener(this);
        binding.itemTvWork.setOnWholeItemClickListener(this);
        binding.itemTvEmil.setOnWholeItemClickListener(this);
        binding.cfkSign.setEnable(false);
        binding.cfkAddress.setEnable(false);
       /* binding.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.r1:
                        binding.llBase.setVisibility(View.VISIBLE);
                        binding.llCom.setVisibility(GONE);
                        break;
                    case R.id.r2:
                        binding.llBase.setVisibility(GONE);
                        binding.llCom.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });*/
        initTabLayout();

        SharedPreferenceUtil.init(this);

        initcomlist();

    }

    @Override
    public void onRefresh() {
        page=1;
        viewModel.getCompanyList(page,limit);
    }

    @Override
    public void onLoadMore() {
        page++;
        viewModel.getCompanyList(page,limit);
    }

    private void initTabLayout() {
        binding.mTabLayout.addTab(binding.mTabLayout.newTab().setText("个人信息"));
        binding.mTabLayout.addTab(binding.mTabLayout.newTab().setText("我的组织"));
        binding.mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        binding.mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    binding.llBase.setVisibility(View.VISIBLE);
                    binding.llCom.setVisibility(GONE);
                } else {
                    binding.llBase.setVisibility(GONE);
                    binding.llCom.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回按钮
            case R.id.iv_back:
                //关闭当前界面
                finish();
                break;
            case R.id.main_corporate:
                //切换企业
                if (mCompanyEntityList.size() > 0) {
                    SwitchingEnterprisesActivity.start(this, mCompanyEntityList, CompanyrequestCode);

                } else {

                }
                break;
            case R.id.iv_user_name:
                //上传头像
                if (!isEdit) {
                    MToast.showToast(PersonInfoActivity.this, "请先点击编辑按钮");
                    return;
                }
                showAlbumPop();
                break;
            case R.id.right_view:
                //加入企业
                JoinCompanyActivity.start(this);
                break;
            case R.id.next_view:
                if (binding.nextView.getText().equals("编辑")) {
                    binding.nextView.setText("保存");
                    isEdit = true;
                    isEdit(true);
                } else {
                    binding.nextView.setText("编辑");
                    isEdit = false;
                    if (viewModel.userBaseEntity.get()==null){
                        MToast.showToast(PersonInfoActivity.this, "获取用户信息失败");
                        return;
                    }
                    if (!TextUtils.isEmpty(viewModel.userBaseEntity.get().getMail()) && !CheckUtils.isEmail(viewModel.userBaseEntity.get().getMail())) {
                        MToast.showToast(PersonInfoActivity.this, "请填写正确的邮箱");
                        return;
                    }
                    viewModel.editBasicInfo();
                    isEdit(false);
                }
                break;
            case R.id.tv_click:
                if (!isEdit) {
                    MToast.showToast(PersonInfoActivity.this, "请先点击编辑按钮");
                }
                break;
            case R.id.tv_click2:
                if (!isEdit) {
                    MToast.showToast(PersonInfoActivity.this, "请先点击编辑按钮");
                }
                break;
        }
    }
    public void initcomlist(){
         enterprisesListAdapter = new SelfEnterprisesListAdapter(this, mlist, requestManager);
        enterprisesListAdapter.setListener(new SelfEnterprisesListAdapter.OnConfigDefaultCompanyListener() {
            @Override
            public void onDefaultConfig(CompanyEntity companyEntity) {
                viewModel.setMainCompany(companyEntity);
            }
        });
        //recycleView设置适配器
        binding.rvEnterprisesList.setAdapter(enterprisesListAdapter);
        viewModel.getCompanyList(page,limit);
    }
    //用户下所有企业
    public void showCompanyList(List<CompanyEntity> data) {
        binding.rvEnterprisesList.refreshComplete();
        binding.rvEnterprisesList.setLoadingMoreEnabled(true);
        if (page==1){
            mlist.clear();
        }
        if (data!=null&&data.size()>0){
            mlist.addAll(data);
        }
        //创建公司列表适配器
        if (mlist != null && mlist.size() > 0) {
            binding.ntscrollView.setVisibility(GONE);
            binding.empty.setVisibility(GONE);
            binding.rvEnterprisesList.setVisibility(View.VISIBLE);
            //EnterprisesListAdapter enterprisesListAdapter = new EnterprisesListAdapter(this, data);
            enterprisesListAdapter.notifyDataSetChanged();

        } else {
            binding.ntscrollView.setVisibility(View.VISIBLE);
            binding.empty.setVisibility(View.VISIBLE);
            binding.rvEnterprisesList.setVisibility(GONE);
        }
    }

    //展开popuwindw
    private void showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow.isShowing()) {
            //满足条件展示
            selectAlbumPopWindow.showDownPopwindow(binding.grayLayout, true);
        }
    }

    //结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 获取到图片的本地路径
                String path = PictureSelector.obtainMultipleResult(data).get(0).getRealPath();
                //保存在文件中
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    //接口上传文件
                    viewModel.uploadAvatar(file);
                    //上传时，出现上传弹窗
                    DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
                }else {
                    MToast.showToast(getApplicationContext(),"获取图片失败！");
                }

            }
        }
        //之前版本设置主企业
        if (resultCode == SwitchingCode && requestCode == CompanyrequestCode) {
            Log.d("onActivityResult==", data.getSerializableExtra("mCompanyEntityList") + "");
            List<CompanyEntity> companyEntities = (List<CompanyEntity>) data.getSerializableExtra("mCompanyEntityList");
            mCompanyEntityList.clear();
            mCompanyEntityList.addAll(companyEntities);
            showCompanyList(mCompanyEntityList);
        }
    }

    //打开相册
    public void openAlbum() {
        PictureSelector.create((Activity) this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)//判断还能选多少张图片
                .compress(true)//是否压缩
                .minimumCompressSize(500)//小于1M不压缩
                .selectionMedia(selectionMedia)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    public void showHeadPortrait(UserBaseEntity entity) {
        mUserEntity = entity;
        if (!TextUtils.isEmpty(entity.getIdentityCard())) {
            isPersonAuth = true;
            binding.itemTvAuth.setContent("已认证");
            binding.itemTvAuth.setColor(getResources().getColor(R.color.color_06C764));
        } else {
            isPersonAuth = false;
            binding.itemTvAuth.setOnWholeItemClickListener(this);
            binding.itemTvAuth.setContent("未认证");
            binding.itemTvAuth.setColor(getResources().getColor(R.color.color_969696));
        }
        if (!TextUtils.isEmpty(entity.getTelephone())) {
            //设置手机号
//            binding.itvRePhone.setText(StringUtil.gonePhone(entity.getTelephone()));
            binding.itemTvPhone.setContent(entity.getTelephone());
        }
        if (!TextUtils.isEmpty(entity.getRealName())) {
            //设置名字
            binding.itemTvName.setContent(entity.getRealName());
        }
        if (entity.getSex().equals("0")) {
            binding.itemTvSex.setContent("女");
        } else if (entity.getSex().equals("1")) {
            binding.itemTvSex.setContent("男");
        }
        if (entity.getBirthday() != null && entity.getBirthday() != 0)
            binding.itemTvAge.setContent(DateUtils.timestampTo13DateNos(entity.getBirthday()));

        renderEditContent("", false);

        //获取基本信息中的头像路径
        entityImage = entity.getImage();
        showAvatar(entityImage);
    }

    public void showAvatar(String avatar) {
        if (TextUtils.isEmpty(avatar)) {
            binding.ivUserName.setImageResource(R.mipmap.def_photo);
        } else {
            //Glide展示图片
            Glide.with(this)
                    //加载设置宽高限制
                    .load(avatar + "?x-oss-process=image/resize,m_fixed,h_100")
                    //显示圆图
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.ivUserName);
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_sex:
                if (isPersonAuth) {
                    MToast.showToast(PersonInfoActivity.this, "实名认证后性别不可修改");
                    return;
                } else if (isEdit) {
                    showSexPop();
                } else {
                    MToast.showToast(PersonInfoActivity.this, "请点击编辑按钮后再进行编辑");
                }
                break;
            case R.id.item_tv_age:
                if (isPersonAuth) {
                    MToast.showToast(PersonInfoActivity.this, "实名认证后出生日期不可修改");
                    return;
                } else if (isEdit) {
                    showTimePop();
                } else {
                    MToast.showToast(PersonInfoActivity.this, "请点击编辑按钮后再进行编辑");
                }
                break;
            case R.id.item_tv_company:
            case R.id.item_tv_work:
            case R.id.item_tv_emil:
                if (!isEdit) {
                    MToast.showToast(PersonInfoActivity.this, "请先点击编辑按钮");
                }
                break;
            case R.id.item_tv_name:
                /*if (isPersonAuth) {
                    MToast.showToast(PersonInfoActivity.this, "实名认证后姓名不可修改");
                    return;
                }*/
                break;
            case R.id.item_tv_phone:
                if (!isEdit) {
                    MToast.showToast(PersonInfoActivity.this, "请先点击编辑按钮");
                } else {
                    Intent intent = new Intent(PersonInfoActivity.this, ChangeMobileActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.item_tv_auth:
                //认证
//                AuthActivity3.start(this);
                CertificationActivity.start(this);
                break;
        }
    }

    private void showSexPop() {
        OptionsPickerView sexOption = new OptionsPickerBuilder(PersonInfoActivity.this, (options1, options2, options3, v) -> {
            String content = viewModel.getSexList().get(options1).getName();
            binding.itemTvSex.setContent(content);
            if (null != viewModel.userBaseEntity && null != viewModel.userBaseEntity.get()){
                if (content.equals("男")) {
                    viewModel.userBaseEntity.get().setSex("1");
                } else {
                    viewModel.userBaseEntity.get().setSex("0");
                }
            }
            sexPosition = options1;
        }).build();
        sexOption.setPicker(viewModel.getSexList());
        sexOption.setSelectOptions(sexPosition);
        sexOption.show();
    }

    //时间选择器
    private void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(PersonInfoActivity.this, (date, v) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            Date noDate = new Date();
            if (date.getTime() > noDate.getTime()) {
                MToast.showToast(PersonInfoActivity.this, "时间不能大于当前日期");
                return;
            }
            binding.itemTvAge.setContent(format);
            viewModel.userBaseEntity.get().setBirthday(DateUtils.dateTo13Timestamp(format));
        }).build();
        timePicker.show();
    }

    public void renderEditContent(String defaultVal, boolean isEdit){
        if (mUserEntity == null){
            mUserEntity = new UserBaseEntity();
            defaultVal = "";
        }
        binding.itemTvCompany.setContent(TextUtils.equals(defaultVal, mUserEntity.getCompanyName()) ? isEdit ? ""  : "--" : mUserEntity.getCompanyName());
        binding.itemTvWork.setContent(TextUtils.equals(defaultVal,mUserEntity.getJob()) ? isEdit ? "" : "--" : mUserEntity.getJob());
        binding.itemTvEmil.setContent(TextUtils.equals(defaultVal,mUserEntity.getMail()) ? isEdit ? ""  : "--" : mUserEntity.getMail());
        binding.cfkAddress.setEditContent(TextUtils.equals(defaultVal,mUserEntity.getAddress()) ? isEdit ? ""  : "--" : mUserEntity.getAddress());
        binding.cfkSign.setEditContent(TextUtils.equals(defaultVal,mUserEntity.getSignature()) ? isEdit ? ""  : "--" : mUserEntity.getSignature());
    }


    private void isEdit(boolean isCanInput) {
        binding.itemTvCompany.setEnable(isCanInput);
        binding.itemTvWork.setEnable(isCanInput);
        binding.itemTvEmil.setEnable(isCanInput);
        binding.cfkAddress.setEnable(isCanInput);
        binding.cfkSign.setEnable(isCanInput);
        binding.itemTvSex.setArrowVisible(isCanInput);
        binding.itemTvAge.setArrowVisible(isCanInput);
        binding.itemTvPhone.setArrowVisible(isCanInput);
        binding.itemTvAuth.setArrowVisible(isCanInput);
        binding.cfkAddress.setShowBottomNumber(isCanInput);
        binding.cfkSign.setShowBottomNumber(isCanInput);

        if (isCanInput) {
            renderEditContent("--", true);
        } else {
            renderEditContent("", false);
        }

        if (isCanInput) {
            binding.tvClick.setVisibility(GONE);
        } else {
            binding.tvClick.setVisibility(View.VISIBLE);
        }
        if (isCanInput) {
            binding.tvClick2.setVisibility(GONE);
        } else {
            binding.tvClick2.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvent event) {
        if (event == null) return;
        if (event.getMessageTag() == EventConstant.EVENT_PHONE_EDIT) {
            //设置手机号
            binding.itemTvPhone.setContent(StringUtil.gonePhone(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "")));
            viewModel.userBaseEntity.get().setTelephone(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
        }
    }
}
